package com.rainy.cloud.gateway.filter;

import com.rainy.cloud.gateway.enums.RootNode;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * @author user
 */
@Component
public class UriFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI uri = exchange.getRequest().getURI();
        String uriPath = uri.getPath();
        RootNode rootNodeTmp = null;
        for (RootNode rootNode : RootNode.getRootNodes()) {
            StringBuffer stringBuffer = new StringBuffer(rootNode.getRootPath());
            stringBuffer.append("/");
            if (uriPath.startsWith(stringBuffer.toString())) {
                rootNodeTmp = rootNode;
                break;
            }
        }

        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri);
        if (null != rootNodeTmp) {
            uriPath = uriPath.replace(rootNodeTmp.getRootPath(), "");
            uriComponentsBuilder.port(Integer.valueOf(rootNodeTmp.getPort()));
        }
        URI newUri = uriComponentsBuilder.replacePath(uriPath).build(true).toUri();
        ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
